package com.lqk.netty.handler;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.lqk.netty.common.protobuf.MessageModule;
import com.lqk.netty.common.execute.MessageTask4Request;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * @author: wyl
 * @date: 2021/7/13
 * @des:
 */
public class ServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 用于记录和管理所有客户端的channle
      */
    public static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    /**
     * 创建线程池
     */
    ThreadPoolExecutor workerPool = new ThreadPoolExecutor(5,
            10,
            60L,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(4000),
            new ThreadPoolExecutor.DiscardPolicy());

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //记录连接数,当触发handlerRemoved，ChannelGroup会自动移除对应客户端的channel
        clients.add(ctx.channel());

        MessageModule.Message request = (MessageModule.Message) msg;
        // 异步处理业务逻辑
        workerPool.submit(new MessageTask4Request(request, ctx));
    }
}
